package cn.chendd.feign.httpclient;

import com.fasterxml.jackson.databind.ObjectMapper;
import feign.MethodMetadata;
import feign.RequestTemplate;
import feign.codec.EncodeException;
import feign.form.spring.SpringFormEncoder;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author chendd
 */
public class HttpFeignFormEncoder extends SpringFormEncoder {

    private ObjectMapper objectMapper;

    public HttpFeignFormEncoder(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
        if (object != null) {
            final Method method = template.methodMetadata().method();
            final FeignUploadFile uploadFile = method.getAnnotation(FeignUploadFile.class);
            if (uploadFile != null) {
                super.encode(object , bodyType , template);
                return;
            }
            try {
                String json = objectMapper.writeValueAsString(object);
                template.body(json.getBytes() , StandardCharsets.UTF_8);
            } catch (Exception e) {
                throw new UnsupportedOperationException(e);
            }
        } else {
            //没有@RequestBody注解参数的处理方式
            super.encode(object , bodyType , template);
        }
    }
}
